package DatabaseManager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import Other.*;
public class CharacterInUniverseTable extends Table{

	/**
	 * The function builds a table object (doesn't actually create it in the database)
	 * @param db_mgr - the database manager
	 * @throws SQLException - thrown in case of an sql exception
	 * @throws ClassNotFoundException - thrown in case of a class not found exception
	 */
	public CharacterInUniverseTable(DBManager db_mgr) throws SQLException, ClassNotFoundException {
		super(db_mgr);
		table_name = "character_in_universe";
		primaryKey = "character_id, universe_id";
		String[] tmp = {"character_id", "universe_id"};
		columns = tmp;
		String[] tmp1 = {null, null};
		foreignKey = tmp1;
		String[] tmp2 = {"INT", "INT"};
		dataTypes = tmp2;
		boolean[] tmp3 = {false, false};
		isDataTypeNull = tmp3;
		isMyISAM = true;
	}

	/**
	 * Returns a page of characters in a given universe.
	 * @param universeId - id of universe
	 * @param pageNumber - number of page
	 * @param entriesPerPage - number of entries per page
	 * @return a list with serverCard that should be in the page
	 * @throws SQLException
	 */
	public List<ServerCard> getCharacterPage(int universeId, int pageNumber,
			int entriesPerPage) throws SQLException {
		
		String where = "universe_id = " + universeId + " AND " 
		+ table_name + ".character_id = fictional_character.character_id";
		String select = "name, hit_points, strength, " + table_name + ".character_id";
		ResultSet rs = null;
		List<ServerCard> characters = null;
		try {
		rs = super.getPage(pageNumber, entriesPerPage, "name", select, where, "fictional_character");
		characters= new ArrayList<ServerCard>();
			while (rs.next()) {
				// preventing user from getting null
				String name = rs.getString(1);
				name = (name == null ? "" : name);
				characters.add(new ServerCardConcrete(name, rs.getInt(3), rs.getInt(2), rs.getInt(4)));
				// mechanism to ensure closing
			}
		} catch (SQLException e) {
			db_mgr.closeLastStatement();
			throw e;
		}
		db_mgr.closeLastStatement();
		return characters;
	}

}
